import { createRouter, createWebHistory } from 'vue-router'

import NavBar from '../components/NavBar.vue'
import SideBar from '../components/SideBar.vue'

// import Home from '../views/Home.vue'

// import About from '../views/About.vue'
// import Detail from '../views/Detail.vue'
// import User from '../views/User.vue'
// import Users from '../views/nested/User.vue'
// import UserProfile from '../views/nested/Profile.vue'
// import Posts from '../views/nested/Posts.vue'
// import NotFound from '../views/NotFound.vue'

const Home = () => import('../views/Home.vue')
const About = () => import('../views/About.vue')
const Detail = () => import('../views/Detail.vue')
const User = () => import('../views/User.vue')
const Users = () => import('../views/nested/User.vue')
const UserProfile = () => import('../views/nested/Profile.vue')
const Posts = () => import('../views/nested/Posts.vue')
const NotFound = () => import('../views/NotFound.vue')

// 创建路由对象
const router = createRouter({
  history: createWebHistory() , // 路由模式  hash: createWebHashHistory()   history: createWebHistory()
  routes: [ // 静态路由表配置，最基本的为路径到组件的映射关系
    // {
    //   path: '/',
    //   redirect: '/index',
    // },
    {
      path: '/index', // 路由路径
      alias: '/',
      // component: Home, // 对应渲染组件，向 default 名称的 router-view 出口渲染
      components: { // 渲染命名视图
        nav: NavBar,
        side: SideBar,
        default: Home,
      },
      meta: {
        title: '首页',
      },
    },
    {
      path: '/about', // 路由路径
      // component: () => import('../views/About.vue'), // 路由懒加载写法
      components: {
        nav: NavBar,
        default: About,
      },
      meta: {
        title: '关于我们',
      },
    },
    {
      path: '/detail',
      // component: () => import('../views/Detail.vue'),
      components: {
        side: SideBar,
        default: Detail,
      },
      meta: {
        title: '商品详情',
      },
    },
    {
      path: '/user/:username',
      name: 'user', // 命名路由
      component: User,
      meta: {
        title: '用户',
      },
    },
    {
      path: '/users',
      component: Users,
      children: [ // 嵌套路由，子路由
        {
          path: 'profile', // 完整路径: /users/profile
          component: UserProfile,
          meta: {
            title: '个人中心',
          },
        },
        {
          path: 'posts', // 完整路径: /users/posts
          component: Posts,
          meta: {
            title: '发表文章',
          },
        },
      ],
      meta: {
        title: '用户管理',
      },
    },
    // 捕获 404
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },
  ],
})

// 全局前置守卫
router.beforeEach((to, from) => {
  // to: 即将进入的目标路由
  // from: 正在离开的当前路由
  // to、from 的结构与组件中的 $route 结构一致
  console.log('离开:', from)
  console.log('进入:', to)

  // 设置标题栏
  document.title = to.meta.title
})

export default router
